import { Divider, Table, Space } from "antd";
import TransLink from "@/components/TransLink";
import React, { useEffect, useImperativeHandle, useState } from "react";
import ButtonsList from "../ButtonsList";
import "./index.less";
import { emptyValueToDefault, returnCustomValue } from "./transData";

const SORTORDER = {
  ASCEND: "ascend",
  DESCEND: "descend",
};
const CustomTable = React.forwardRef((props, ref) => {
  const {
    columns = [],
    dataObj = {},
    loading,
    initValue = {},
    multipleButtons = [],
    isShowHideTriggerButton = false,
    onRowSelectChange,
    ...Props
  } = props;
  // 内部变量，页数，页码，排序，过滤等
  const [tableParams, setTableParams] = useState(initValue);
  const [selectedRows, setSelectedRows] = useState([]); // 多选的row
  const [selectedKeys, setSelectedKeys] = useState([]); // 多选的key
  // 多选按钮禁用, 默认上来是禁用状态
  const [mulBtnsDisabled, setMulBtnsDisabled] = useState(true);
  useEffect(() => {
    setTableParams({ ...initValue });
  }, [JSON.stringify(initValue)]);

  useEffect(() => {
    setMulBtnsDisabled(!selectedKeys?.length);
  }, [selectedKeys?.length]);

  // 暴露给父组件的方法
  useImperativeHandle(ref, () => ({
    changeTableParams: (params) => {
      setTableParams({
        ...tableParams,
        ...params,
      });

      // 清空多选
      setSelectedKeys([]);
      onRowSelectChange?.([], []);
    },
    clearSelectedKeys: () => {
      setSelectedKeys([]);
      onRowSelectChange?.([], []);
    },
  }));

  // 提供组件转换数据的方法
  const transLinkTableCol = (item) => {
    return {
      ...item,
      render: (text, record) => {
        const {
          linkUrl,
          linkSearch = () => {},
          isInner = false,
        } = item.linkConfig;
        let searchConfig = linkSearch(record);
        if (typeof searchConfig !== "object") {
          searchConfig = {};
        }
        return (
          <TransLink
            linkUrl={linkUrl}
            searchConfig={searchConfig}
            isInner={isInner}
          >
            {text}
          </TransLink>
        );
      },
    };
  };

  const transOperationTableCol = (item) => {
    return {
      ...item,
      render: (text, record) => {
        // 当operationItems 是方法时，执行接受处理完的数组并进行下面的 组装
        const operationItems = returnCustomValue(item.operationItems, record);

        // 过滤掉隐藏项
        const showOperationItems = operationItems.filter(
          (it) => !returnCustomValue(it.hidden, record)
        );
        // 组装
        return (
          <div>123123</div>
          // <OperationGroup
          //   count={2}
          //   trigger={["click"]}
          //   size={1}
          //   split={<Divider type="vertical" />}
          //   getPopupContainer={() =>
          //     document.querySelector(".csp-mng-table-content")
          //   }
          // >
          //   {showOperationItems.map((it) => {
          //     return (
          //       <>
          //         {it.render ? (
          //           it.render(record)
          //         ) : (
          //           <a
          //             onClick={() => it.clickAction(record)}
          //             className={`${style.operationItems} dt-custom-theme-color`}
          //           >
          //             {it.text}
          //           </a>
          //         )}
          //       </>
          //     );
          //   })}
          // </OperationGroup>
        );
      },
    };
  };

  const transSorterTableCol = (item) => {
    return {
      ...item,
      sorter: (a, b) => {
        const field = item.dataIndex;
        const type = typeof a[field];
        if (type === "number") {
          return a[field] - b[field];
        } else if (type === "string") {
          return a[field] > b[field];
        }
      },
    };
  };
  // 列表change
  const onTableChange = (pagination, filters, sorter) => {
    const { current, pageSize } = pagination;
    const orderBy = sorter.order ? sorter.field : null;
    const isDesc = sorter.order ? sorter.order === SORTORDER.DESCEND : null;
    setTableParams({
      ...tableParams,
      pageNum: current,
      pageSize,
      isDesc,
      orderBy,
    });

    if (props.onTableChange) {
      props.onTableChange({
        ...pagination,
        isDesc,
        orderBy,
        filters,
      });
    }
    setSelectedKeys([]);
    setSelectedRows([]);
    onRowSelectChange?.([], []);
  };
  const transMultipButtons = () => {
    if (mulBtnsDisabled) {
      // 如果是禁用状态，则每项加一个disabled属性
      return multipleButtons.map((item) => {
        return {
          ...item,
          disabled: item.disabled ?? true,
        };
      });
    }
    return multipleButtons;
  };
  const renderInlineHeader = () => {
    return (
      <ButtonsList buttonsConfig={transMultipButtons()} params={selectedRows} />
    );
  };

  // 转换columns变成表格组件需要的形式 转换link，操作，默认排序行为
  const transColumns = (item) => {
    let cloneItem = { ...item };
    if (cloneItem.useDefaultSorter) {
      cloneItem = transSorterTableCol(cloneItem);
    }
    if (cloneItem.linkConfig) {
      cloneItem = transLinkTableCol(cloneItem);
    }
    if (cloneItem.operationItems) {
      cloneItem = transOperationTableCol(cloneItem);
    }
    // 当没有render时，添加默认转换异常值的render函数
    if (!cloneItem.render) {
      cloneItem.render = (text) => {
        return emptyValueToDefault(text);
      };
    }
    return cloneItem;
  };

  // 回显默认的排序
  const showDefaultSortOrder = (columns) => {
    const { isDesc, orderBy } = initValue;
    if (isDesc && orderBy) {
      return columns.map((item) => {
        if (item.dataIndex === orderBy) {
          return {
            ...item,
            defaultSortOrder: isDesc ? SORTORDER.DESCEND : SORTORDER.ASCEND,
          };
        }
        return item;
      });
    }
    return columns;
  };

  const tranedColumns = showDefaultSortOrder(
    columns
      .filter((item) => {
        if (item.hidden) {
          return false;
        }
        return true;
      })
      .map((item) => {
        return transColumns(item);
      })
  );

  const rowSelectionObj = {
    onChange: (selectedRowKeys, selectedRows) => {
      setSelectedKeys(selectedRowKeys);
      setSelectedRows(selectedRows);
      if (selectedRows.length > 0) {
        setMulBtnsDisabled(false);
      } else {
        setMulBtnsDisabled(true);
      }
      onRowSelectChange?.(selectedRowKeys, selectedRows);
    },
    selectedRowKeys: selectedKeys,
    checkAllPosition: "top",
  };

  // 拼装Table组件的props
  const tableProps = {
    rowSelection:
      (multipleButtons || []).some((item) => item.disabled !== false) &&
      rowSelectionObj,
    columns: tranedColumns,
    loading,
    onChange: onTableChange,
    pagination: {
      total: dataObj.total,
      current: Number(tableParams.pageNum) || 1,
      pageSize: tableParams.pageSize || 10,
    },
    ...Props,
  };

  return (
    <>
      <div className="topContent">
        <Space size={8}>
          {multipleButtons.length > 0 && renderInlineHeader()}
        </Space>
      </div>
      <Table
        rowKey={(record) => record.id}
        columnController={{
          hideTriggerButton: isShowHideTriggerButton, // 是否显示表格组件内置的“列配”按钮
        }}
        {...tableProps}
        dataSource={dataObj?.dataSource}
        className="tableWrapper"
      />
    </>
  );
});

export default CustomTable;
